package com.qing.springcloud.aspect;

import cn.hutool.core.util.StrUtil;
import com.qing.springcloud.annotation.RequireLogin;
import com.qing.springcloud.annotation.SkipLoginCheck;
import com.qing.springcloud.exception.ExceptionTypeEnum;
import com.qing.springcloud.exception.BusinessException;
import com.qing.springcloud.service.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

/**
 * 登录拦截切面类，用于检查用户是否登录
 */
@Aspect
@Component
//@Order(1)
public class LoginInterceptorAspect {

    @Autowired
    private LoginService loginService;

    @Before("@annotation(com.qing.springcloud.annotation.RequireLogin) || @within(com.qing.springcloud.annotation.RequireLogin)")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 检查是否有 SkipLoginCheck 注解，有则跳过登录校验
        if (method.isAnnotationPresent(SkipLoginCheck.class) ||
                method.getDeclaringClass().isAnnotationPresent(SkipLoginCheck.class)) {
            return;
        }

        // 检查类或方法上是否有 @RequireLogin 注解
        if (method.isAnnotationPresent(RequireLogin.class) ||
                method.getDeclaringClass().isAnnotationPresent(RequireLogin.class)) {
           joinPoint.getArgs();

            // 获取 HttpServletRequest 对象
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                throw new BusinessException("无法获取请求信息");
            }
            HttpServletRequest request = attributes.getRequest();
            // 获取 Authorization 请求头
            String authorization = request.getHeader("Authorization");

            if (StrUtil.isEmpty(authorization)) {
                throw new BusinessException(ExceptionTypeEnum.USER_NOT_LOGIN);
            }
            loginService.checkLogin(authorization);
        }

    }
}